<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :showBack="true">
  </pageHeader>
  <div class="main">
    <div class="title">
      <div class="icon"></div>
      <p>基础信息</p>
    </div>
    <div class="form">
      <a-form ref="formRef" :model="form" auto-label-width style="width: 70%" :rules="rules">
        <a-row :gutter="24" justify="space-between">
          <a-col :span="11">
            <a-form-item show-colon label="生产订单编号" label-col-flex="100px" required>
              <a-input disabled placeholder="自动生成生产订单编号" v-model="form.data.number" />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item show-colon field="type" label="订单类型" required>
              <a-select v-model="form.data.type" placeholder="请选择" disabled>
                <a-option :value="1">面向库存订单</a-option>
                <a-option :value="2">面向销售订单</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="type === 2" :gutter="24" justify="space-between">
          <a-col :span="11">
            <a-form-item show-colon label="关联销售订单号">
              <a-input placeholder="系统自动读取" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item show-colon field="customName" label="客户名称">
              <!-- <a-input
                v-model="form.data.customName"
                placeholder="请输入"
                :disabled="look === 2"
              /> -->
              <a-select :disabled="look === 2" v-model="form.data.customId" placeholder="请选择" allow-search>
                <a-option v-for="item in clientList.data" :key="item.id" :value="item.id">{{ item.name }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" justify="space-between">
          <a-col :span="11">
            <a-form-item show-colon label="部门名称">
              <!-- <a-input
                v-model="form.departmentName"
                placeholder="请选择部门名称"
              /> -->
              <sectionSelect v-model="form.data.departmentId" placeholder="请选择部门名称" :isSearch="true" @selectSection="changeSectionFn" :disabled="look === 2" />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item show-colon label="计划人">
              <a-input placeholder="系统自动读取当前操作人" disabled />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" justify="space-between">
          <a-col :span="11">
            <a-form-item show-colon label="创建时间">
              <a-input placeholder="获取电脑当前时间" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item show-colon label="创建人">
              <a-input placeholder="系统自动读取当前操作人" disabled />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item field="remark" show-colon label="备 注">
              <a-textarea :disabled="look === 2" auto-size style="min-height: 100px" v-model="form.data.remark" placeholder="请输入" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="title" style="padding-bottom: 10px; border-bottom: 1px solid #e4e4e4">
      <div class="icon"></div>
      <p>物料明细</p>
    </div>
    <div class="form">
      <a-form auto-label-width :model="form" style="width: 70%" :rules="rules">
        <a-row :gutter="24" justify="space-between">
          <a-col :span="11">
            <a-form-item show-colon label="物料编码" label-col-flex="100px" required>
              <a-input disabled v-model="form.data.material.number" />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item show-colon field="type" label="物料名称" required>
              <a-input disabled v-model="form.data.material.name" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" justify="space-between">
          <a-col :span="11">
            <a-form-item show-colon label="规格型号">
              <a-input disabled v-model="form.data.material.spec" />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item show-colon field="customName" label="基本单位">
              <a-input disabled v-model="form.data.material.basicUnit" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" justify="space-between">
          <a-col :span="11">
            <a-form-item show-colon label="生产订单数量">
              <a-input-number :min="1" disabled v-model="form.data.planProduceNumber" />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item show-colon label="紧急等级">
              <a-select placeholder="请选择" v-model="form.data.emergencyLevel" :disabled="look === 2">
                <a-option v-for="value in emergencyLevel" :value="value.id" :key="value.id">{{ value.value }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" justify="space-between">
          <a-col :span="11">
            <a-form-item show-colon label="计划开工时间">
              <a-date-picker value-format="x" :disabled="look === 2" v-model="form.data.planBeginAt" />
            </a-form-item>
          </a-col>
          <a-col :span="11">
            <a-form-item show-colon label="计划完工时间">
              <a-date-picker value-format="x" :disabled="look === 2" v-model="form.data.planEndAt" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item field="remark" show-colon label="关联生产BOM">
              <!-- <a-input disabled v-model="form.data.material.basicUnit" /> -->
              <div style="display: flex; flex-direction: column; width: 100%">
                <p style="padding: 0; margin: 10px 0 18px 0">
                  {{
                    form.data.material.bomCode
                      ? form.data.material.bomCode
                      : '暂无'
                  }}
                </p>
                <a-table :bordered="{ cell: true }" :pagination="false" :columns="columnsBOM" :data="form?.data?.material?.bomList" />
              </div>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item field="remark" show-colon label="工艺路线">
              <!-- <a-input disabled v-model="form.data.material.basicUnit" /> -->
              <div style="display: flex; flex-direction: column; width: 100%">
                <p style="padding: 0; margin: 10px 0 18px 0">
                  {{
                    form.data.material.productModel?.routerName
                      ? form.data.material.productModel.routerName
                      : '暂无'
                  }}
                </p>
                <a-table :bordered="{ cell: true }" :pagination="false" :columns="columns" :data="form.data.material.productModel?.productGroupModel" />
              </div>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-if="type === 2">
          <a-col :span="24">
            <a-form-item field="remark" show-colon label="交货要求">
              <!-- <a-input disabled v-model="form.data.material.basicUnit" /> -->
              <p v-if="form.data.orderDelivery?.length === 0">暂无</p>
              <a-table style="width: 100%" v-else :bordered="{ cell: true }" :pagination="false" :show-header="false" :columns="columnsTime" :data="form.data.orderDelivery">
                <template #time="record">
                  {{
                    `${dayjs(record.planEndAt).format('YYYY-MM-DD HH:MM:ss')}`
                  }}
                </template>
              </a-table>
              <!-- <a-input disabled placeholder="暂无" /> -->
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </div>
  <div class="foot" v-if="look === 1">
    <a-space style="margin-right: 20px">
      <a-button @click="router.back()"> 取消 </a-button>
      <a-button type="primary" @click="updata"> 提交 </a-button>
    </a-space>
  </div>
</template>

<script lang="ts" setup>
import { GetProductBomTree } from '@/api/FactoryModeling';
import dayjs from 'dayjs';
import { GetClientList } from '@/api/order-management/client-management/client-list';
import { reactive, ref, computed } from 'vue';
import { GetOrderDetail } from '@/api/order-management/client-order/index';
import {
  PutProduceOrders,
  GetProduceOrderDetails,
} from '@/api/produce-management/produce-list/index';
import type {
  ProduceOrder,
  Tmaterial,
} from '@/api/produce-management/produce-list/type';
import sectionSelect from '@/components/sectionSelect/index.vue';
import pageHeader from '@/components/page-header/index.vue';
import { useRouter, useRoute } from 'vue-router';
import { cloneDeep } from 'lodash';
import { Message } from '@arco-design/web-vue';

const emergencyLevel = [
  { id: 1, value: '一般' },
  { id: 2, value: '紧急' },
  { id: 3, value: '加急' },
  { id: 4, value: '特急' },
];
const columns: any = [
  {
    title: '序号',
    dataIndex: 'index',
    align: 'center',
  },
  {
    title: '工序名称',
    dataIndex: 'name',
    align: 'center',
  },
  {
    title: '生产方式',
    dataIndex: 'productionMethod',
    align: 'center',
  },
  {
    title: '生产类型',
    dataIndex: 'processType',
    align: 'center',
  },
  {
    title: '是否报工',
    dataIndex: 'groupDataTypeName',
    align: 'center',
  },
];
const columnsBOM: any = [
  {
    title: '序号',
    dataIndex: 'index',
    align: 'center',
  },
  {
    title: '产品编码',
    dataIndex: 'bomName',
    align: 'center',
  },
  {
    title: '产品名称',
    dataIndex: 'bomName',
    align: 'center',
  },
  {
    title: '型号规格',
    dataIndex: 'bomName',
    align: 'center',
  },
  {
    title: '生产BOM',
    dataIndex: 'groupDataTypeName',
    align: 'center',
  },
];
const columnsTime: any = [
  {
    title: '时间名字',
    dataIndex: 'deliveryTimeName',
    align: 'center',
    width: 200,
    cellStyle: {
      backgroundColor: '#f2f2f2',
    },
  },
  {
    title: '时间',
    dataIndex: 'deliveryTime',
    align: 'center',
    width: 200,
    slotName: 'time',
  },
  {
    title: '数量名字',
    dataIndex: 'numberName',
    align: 'center',
    width: 200,
    cellStyle: {
      backgroundColor: '#f2f2f2',
    },
  },
  {
    title: '数量',
    dataIndex: 'number',
    align: 'center',
    width: 200,
  },
];

const breadCrumb: string[] = ['生产管理', '生产订单列表', '编辑生产订单'];
const router = useRouter();
const route = useRoute();
const clientList: any = reactive({ data: [] });
const form = reactive<{ data: ProduceOrder & { material: Tmaterial } }>({
  data: { material: { productModel: {} } },
});
const id = ref(Number(route.query.id));
const type = ref(Number(route.query.type));
const look = ref(Number(route.query.look));
const formRef = ref();
let tableRef = ref();
const rules = {
  type: [
    {
      required: true,
      message: '请选择订单类型',
    },
  ],
};
const title = computed(() => {
  if (look.value === 1) {
    return '编辑生产订单';
  } else return '生产订单详情';
});
// 返回箭头
const back = () => {
  router.back();
};
const flattenTree = (tree: any[]) => {
  const flatArray: any[] = [];
  const flatten = (node: any) => {
    flatArray.push(node);
    if (node.children?.length > 0) {
      node.children.forEach((child: any) => flatten(child));
      delete node.children;
    }
  };

  tree.forEach((node) => flatten(node));
  return flatArray;
};
const getData = async () => {
  const res = await GetProduceOrderDetails({ id: id.value });
  const bomId = res.bomId;

  form.data = {
    ...res,
    material: {
      ...res.material,
      productModel: { ...res.material?.productModel },
    },
  };
  if (form.data.saleOrderId) {
    const orderDetail = await GetOrderDetail({ id: form.data.saleOrderId });
    const {
      clientCompanyName: customName,
      clientCompanyId: customId,
      number: saleOrderNumber,
      orderDelivery,
    } = orderDetail;
    let delivery: any = [];
    orderDelivery.forEach((ele: any) => {
      if (ele.name === form.data.material.name) {
        delivery = ele.items.map((ele: any, index: number) => {
          ele.deliveryTimeName = `交货时间${index + 1}`;
          ele.numberName = '交货数量';
          return ele;
        });
      }
    });
    form.data.customId = customId;
    form.data.saleOrderNumber = saleOrderNumber;
    form.data.customName = customName;
    form.data.orderDelivery = delivery;
  }
  const res3 = await GetProductBomTree(bomId);
  form.data.material.bomList = flattenTree([res3]);
  form.data.material.bomList.forEach((ele, index) => {
    ele.index = index + 1;
  });
  const res2 = await GetClientList({ page: 1, size: -1 });
  clientList.data = res2.content;
  if (form.data.material.productModel?.productGroupModel) {
    form.data.material.productModel.productGroupModel.forEach((ele, index) => {
      ele.index = index + 1;
      if (ele.groupDataType === 1) {
        ele.groupDataTypeName = '是';
      } else ele.groupDataTypeName = '否';
    });
  } else if (form.data.material.productModel) {
    form.data.material.productModel.productGroupModel = [];
  } else {
    form.data.material.productModel = {};
    form.data.material.productModel.productGroupModel = [];
  }
};
getData();
const changeSectionFn = (e: number) => {
  form.data.departmentId = e;
};

const updata = async () => {
  try {
    const newData = cloneDeep(form.data);
    newData.planBeginAt = +new Date(newData.planBeginAt as unknown as string);
    newData.planEndAt = +new Date(newData.planEndAt as unknown as string);
    await PutProduceOrders({ ...newData });
    router.back();
  } catch (error) {
    console.log(error);
  }
};
</script>

<style lang="less" scoped>
.main {
  width: 100%;
  padding: 20px;
  .title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .icon {
      background-color: #3d7eff;
      width: 5px;
      height: 20px;
      border-radius: 5px;
      margin-right: 10px;
    }
    p {
      font-size: 16px;
      padding: 0;
      margin: 0;
    }
  }
  .form {
    width: 100%;
    display: flex;
    justify-content: center;
  }
}
.foot {
  padding-top: 10px;
  margin-top: 10px;
  border-top: 1px solid #e4e4e4;
  display: flex;
  justify-content: end;
}
</style>
